package com.cskaoyan.service.user;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.MallBrand;
import com.cskaoyan.bean.MallBrandExample;
import com.cskaoyan.mapper.MallBrandMapper;
import com.cskaoyan.model.bo.PageBo;
import com.cskaoyan.model.bo.user.BrandCreateBo;
import com.cskaoyan.model.vo.user.BrandListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @program: project-market
 * @description:
 * @author: zhijie
 * @create: 2021-11-30 23:28
 **/
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    MallBrandMapper mallBrandMapper;

    @Override
    public BrandListVo brandList(String id, String name, PageBo pageBo) {
        //在查询之前使用分页
        PageHelper.startPage(pageBo.getPage(), pageBo.getLimit());
        MallBrandExample example = new MallBrandExample();
        example.setOrderByClause(pageBo.getSort() + " " + pageBo.getOrder());
        MallBrandExample.Criteria criteria = example.createCriteria();
        if (id != null && !StringUtils.isEmpty(id)) {
            criteria.andIdEqualTo(Integer.parseInt(id));
        }
        if (name != null && !StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MallBrand> mallBrands = mallBrandMapper.selectByExample(example);
        //得到查询的数量
        PageInfo<MallBrand> info = new PageInfo<>(mallBrands);
        long total = info.getTotal();
        int pages = info.getPages();
        BrandListVo vo = new BrandListVo();
        vo.setLimit(pageBo.getLimit());
        vo.setPage(pageBo.getPage());
        vo.setPages(pages);
        vo.setTotal(total);
        vo.setList(mallBrands);
        return vo;
    }

    @Override
    public MallBrand brandCreate(BrandCreateBo bo) {
        MallBrand mallBrand = new MallBrand();
        Date date = new Date();
        mallBrand.setAddTime(date);
        mallBrand.setUpdateTime(date);
        mallBrand.setFloorPrice(bo.getFloorPrice());
        mallBrand.setDesc(bo.getDesc());
        mallBrand.setPicUrl(bo.getPicUrl());
        mallBrand.setName(bo.getName());
        MallBrandExample example = new MallBrandExample();
        int i = mallBrandMapper.insertSelective(mallBrand);
        if (i == 1) {
            return mallBrand;
        }
        return null;
    }

    @Override
    public MallBrand brandUpdate(MallBrand mallBrand) {
        mallBrand.setUpdateTime(new Date());
        int i = mallBrandMapper.updateByPrimaryKeySelective(mallBrand);
        if (i == 1) {
            return mallBrand;
        }
        return null;
    }

    @Override
    public void brandDelete(MallBrand mallBrand) {
        mallBrand.setDeleted(true);
        mallBrandMapper.updateByPrimaryKeySelective(mallBrand);
    }
}
